package com.lianniu.web.captcha;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lianniu.web.base.BaseResult;
import com.lianniu.web.constants.ErrorCode;
import com.lianniu.web.util.CaptchaUtil;
import com.lianniu.web.util.StringUtil;
import com.lianniu.redis.RedisUtils;


/**
 * 
 * @ClassName: LoginFilterController
 * @Description: TODO

 * @date: 2016年3月16日 下午7:23:24
 */
@Controller
@RequestMapping("/rest")
public class CaptchaController {
  private final static Logger logger = Logger.getLogger(CaptchaController.class);
  private final static int TIME=10*60;

  private static RedisUtils redisUtils;

  /**
   * 
   * @Description：根据codeUuid，生成验证码图片和验证码；用codeUuid做key，验证码为值，存储到redis；返回用户验证码图片；
   * @Param: codeUuid：用户的验证码唯一标示。
   * @Return:返回值

   * @Date:作成日期
   */
  @RequestMapping(value = {"/genCaptchaImage"}, method = RequestMethod.GET)
  public @ResponseBody
  BaseResult genCaptchaImage(HttpServletRequest request, String codeUuid) {
    if (StringUtil.isEmpty(codeUuid)) {
      return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode, ErrorCode.ParaCheckErrorRetInfo);
    }

    CaptchaUtil tool = new CaptchaUtil();
    StringBuffer code = new StringBuffer();
    BufferedImage image = tool.genRandomCodeImage(code);
    logger.info(">>> random code =: " + code);
    try {

      File imageFile =
          new File(request.getSession().getServletContext().getRealPath("/") + "capchaImage/"
              + codeUuid + ".jpg");
      // 将内存中的图片通过流动形式输出到客户端
      ImageIO.write(image, "JPEG", new FileOutputStream(imageFile));
      String imageUrl = "capchaImage/" + codeUuid + ".jpg";
      RedisUtils redisUtils = new RedisUtils();
      redisUtils.setTimeOut("codeUuid:" + codeUuid, code.toString(),TIME);
      return BaseResult.success(imageUrl);
    } catch (Exception e) {
      e.printStackTrace();
      return BaseResult.exception(e.getMessage());
    }



  }
  
  
  /**
   * 
   * @Description：根据codeUuid,在redis 里面校验验证码code是否正确；
   * @Param:codeUuid，用户验证码uuid； code，用户输入的验证码
   * @Return:返回值

   * @Date:作成日期
   */
  @RequestMapping(value = {"/validCaptchaCode"}, method = RequestMethod.GET)
  public @ResponseBody
  BaseResult validCaptchaCode(HttpServletRequest request, String codeUuid,String code) {
    if (StringUtil.isEmpty(codeUuid)) {
      return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode, ErrorCode.ParaCheckErrorRetInfo);
    }
    if (StringUtil.isEmpty(code)) {
      return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode, ErrorCode.ParaCheckErrorRetInfo);
    }

    
    try {
      
      RedisUtils redisUtils = new RedisUtils();
      if(RedisUtils.get("codeUuid:" + codeUuid).equals(code))
      {
        return BaseResult.success();
      }
      else
      {
        return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode, ErrorCode.ParaCheckErrorRetInfo);
      }
      
    } catch (Exception e) {
      return BaseResult.exception(e.getMessage());
    }



  }


}
